<?php
	class Pay extends MY_controller{
		function __construct(){
			error_reporting(E_ALL ^ E_NOTICE);
			parent::__construct();
		}

		function wx_notify(){

			$order_log['status'] = 0; //接受通知成功
			$order_log['pay_type'] = '1';
			// $order_log['add_time'] = time();
			$this->db->insert("o2o_school_pay_logs", $order_log);

			ini_set('date.timezone', 'Asia/Shanghai');
	        $xml = file_get_contents("php://input");
	        libxml_disable_entity_loader(true);
	        $wx_order = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
	        if(empty($wx_order)){
	        	echo '缺少数据';exit;
	        }
	        /*if(!$wx_order){
	        	$wx_order = json_decode('{"appid":"wx89e30cde7b71c0c3","attach":"291","bank_type":"CFT","cash_fee":"3000","fee_type":"CNY","is_subscribe":"Y","mch_id":"1291368601","nonce_str":"09qpifsztlkber26vh3oxm4audgw1y87","openid":"o_zV7jsPTDH00xQutbMIHWwYwe2E","out_trade_no":"291","result_code":"SUCCESS","return_code":"SUCCESS","sign":"E1FD8313D47739C07ECEE656B57B2599","time_end":"20170615204122","total_fee":"3000","trade_type":"JSAPI","transaction_id":"4000962001201706155877847818"}', true);
	        }*/
	        $order_log['status'] = 1; //接受通知成功
			$order_log['pay_type'] = 1;
			$order_log['order_id'] = $wx_order['out_trade_no'];
			$order_log['order_detail'] = json_encode($wx_order);
			// $order_log['add_time'] = time();
			$this->db->insert("o2o_school_pay_logs", $order_log);

			$wx_config_data = $order_info = array();



	        if(!empty($wx_order)){
	        	$order_info = get_field_by_where("shopping_orders", "*", "order_id='{$wx_order['out_trade_no']}'");
	        	if(empty($order_info)){
					//查询不到订单，不用再继续发送了
					echo '查询不到订单';
					exit;
				}

	        	$wx_config_data = get_field_by_where("o2o_school_wx_config", "*", "school_id='{$order_info['school_id']}'");
				$wx_config['appid'] = $wx_config_data['app_id'];
			    $wx_config['mch_id'] = $wx_config_data['mch_id'];
			    $wx_config['apikey'] = $wx_config_data['apikey'];
			    $wx_config['sslcertPath'] = $wx_config_data['apiclient_cert'];
			    $wx_config['sslkeyPath'] = $wx_config_data['apiclient_key'];
			    $wx_config['notify_url'] = $this->config->item("wx_pay_notify_url");
			    require_once 'third_party/wxpayApi/wxpay.php';
		        $weixin_pay = new wxpay($wx_config);
	        }

	        if ($order_info['order_status'] == 1 || $order_info['order_status'] == 2) {
				echo '订单已经支付过';
	            $weixin_pay->response_back("SUCCESS"); //回复微信服务器，通知成功，已经支付，业务已经更新，停止通知。
	            exit();
	        }

	        if(!$wx_config_data || empty($wx_order)){
	        	echo '微信配置不存在或者微信POST数据为空';
		    	$weixin_pay->response_back("FAIL");	//该学校暂时未配置微信支付，回复微信继续发送通知
		    	exit;
		    }

		    //检查通信是否成功；签名是否成功；签名校验是否成功
	        if ($wx_order == null or $wx_order['return_code'] == 'FAIL' || !$weixin_pay->validate($wx_order)) {
	        	echo '签名验证失败';
	            $weixin_pay->response_back("FAIL"); //回复微信服务器，通知失败，继续发通知。
	            exit();
	        }

	        $order_log['status']       = 2; //2、验证成功
	        // $order_log['add_time']     = time();
	        $this->db->insert("o2o_school_pay_logs", $order_log);

	        $wx_order_total_fee = round($wx_order['total_fee'] / 100, 2); //将微信订单付款总金额转换为 元
	        if ($wx_order['result_code'] == 'SUCCESS' && $wx_order['time_end'] != '' /*&& $order_info['total_order_amount'] == $wx_order_total_fee*/) {
	        	//佣金
	        	$this->load->model("Users");
	        	$user_commission = $this->Users->get_user_commission($wx_order['out_trade_no']);
	        	if(count($user_commission > 0)){
	        		foreach ($user_commission as $key => $value) {
	        			$this->db->where("user_id", $value['user_id']);
						$this->db->set("balance", "balance + {$value['commission']}", false);
						$this->db->set("commission_total", "commission_total + {$value['commission']}", false);
						$this->db->update("user_account");
						if($this->db->affected_rows() > 0){
							$this->db->where("id", $value['id']);
							$this->db->update("user_commission", array("status" => 1));
						}
	        		}
	        	}

	        	//扣网校视频课激活码
	        	/*if($order_info['order_type'] == 1){
					$time = time();
					$today_time = strtotime(date('Y-m-d'));
		        	$sql = "UPDATE {$this->db->dbprefix}o2o_school_video_user_codes SET status = 2, use_uid='{$order_info['buyer_user_id']}', use_time='{$time}', order_id='{$wx_order['out_trade_no']}' WHERE school_id = '{$order_info['school_id']}' AND status = 1 AND expire_time >= '{$today_time}' ORDER BY id ASC LIMIT 1";
		        	$this->db->query($sql);
		        	if($this->db->affected_rows() > 0){
		        		$this->db->where("id", $order_info['school_id']);
						$this->db->set("item_num", "item_num - 1", false);
						$this->db->update("o2o_school");
		        	}
	        	}*/

	            //记录订单操作数据库日志
	            $order_log['status']   = 3; //3、付款成功
	            // $order_log['add_time'] = time();
	            $this->db->insert("o2o_school_pay_logs", $order_log);

	            $order_data['payment_method']  = 1;	//支付方式（1：微信支付，2：支付宝）
	            $order_data['payment_status']  = 2; //支付状态：0未支付1支付中2支付成功3支付失败
	            $order_data['payment_time']    = strtotime($wx_order['time_end']); //付款时间
	            $order_data['payment_on']      = $wx_order['transaction_id']; //第三方支付交易号
	            $order_data['payment_money_amount']     = $wx_order['total_fee'] / 100; //实付金额
	            $order_data['buyer_account']   = $wx_order['openid']; //微信openid
	            $order_data['order_detail']    = json_encode($wx_order);
	            $order_data['order_status']    = 1;	//订单确认成功，订单扣除激活码
	            $this->db->update('shopping_orders', $order_data, array('order_id' => $wx_order['out_trade_no']));

	            $order_item = get_field_by_where("shopping_order_item", "*", "order_id='{$order_info['order_id']}'");

	            if($order_item){
					if($order_info['order_type'] > 0 && $order_info['order_type'] < 4){
						$push_jihuo_code = false;
						if($order_info['order_type'] == 2 || $order_info['order_type'] == 3){
							$use_status = 1;
							$push_jihuo_code = true;
						}else{
							$course_info = get_field_by_where("course", "school_id", "id='{$order_item['course_id']}'");
							if($course_info['school_id'] > 0){
								$use_status = 1;
								$push_jihuo_code = true;
							}else{
								$use_status = $this->deduct_code($order_info, $order_item);
							}
						}
						if($push_jihuo_code){
							$time = time();
							$use_code_data['course_id'] = $order_item['course_id'];
							$use_code_data['course_type'] = $order_info['order_type'];
							$use_code_data['user_id'] = $order_info['buyer_user_id'];
							$use_code_data['code'] = 'schoo_course';
							$use_code_data['order_num'] = $order_info['order_num'];
							$use_code_data['school_id'] = $order_info['school_id'];
							$use_code_data['add_time'] = $time;
							$use_code_data['effective_time'] = $order_item['effective_time'];
							$this->db->insert("o2o_student_course", $use_code_data);
						}
					}elseif($order_info['order_type'] == 4){
						$subject_info = get_field_by_where("b_subject", "school_id", "id='{$order_item['course_id']}'");
						if($subject_info['school_id'] > 0){
							$use_status = 1;
							$push_jihuo_code = true;
						}else{
							$use_status = $this->deduct_code($order_info, $order_item);
						}
					}elseif($order_info['order_type'] == 5){
						$use_status = $this->deduct_code($order_info, $order_item);
					}

					if($use_status == 1){
						$this->db->update('shopping_orders', array('order_status' => 2), array('order_id' => $wx_order['out_trade_no']));	//成功扣除激活码
						//插入有效期表的数据,先查询是否存在有效期数据,如果有就更新，没有就插入
						$time = time();
						$where = "data_type='{$order_info['order_type']}' AND data_id='{$order_item['course_id']}' AND uid='{$order_info['buyer_user_id']}'";
						$terms_info = get_field_by_where("o2o_student_item_terms", "*", $where);
						$terms_data['school_id'] = $order_info['school_id'];
						$terms_data['data_type'] = $order_info['order_type'];
						$terms_data['data_id'] = $order_item['course_id'];
						$terms_data['uid'] = $order_info['buyer_user_id'];
						$terms_data['lose_time'] = 3600 * 24 * $order_item['effective_time'] + $time;
						$terms_data['last_order_id'] = $wx_order['out_trade_no'];
						if($terms_info){
							if($terms_info['lose_time'] > $time){
								$terms_data['lose_time'] = 3600 * 24 * $order_item['effective_time'] + $terms_info['lose_time'];
							}
							$this->db->where("id", $terms_info['id']);
							$this->db->update("o2o_student_item_terms", $terms_data);
						}else{
							$this->db->insert("o2o_student_item_terms", $terms_data);
						}
					}
				}
				$weixin_pay->response_back("SUCCESS"); //回复微信服务器，通知成功，支付成功，停止通知。
				exit();
	        } else {
	        	echo '订单验证失败';
	            $weixin_pay->response_back("FAIL"); //回复微信服务器，未支付，继续发通知。
	        }
		}

		function deduct_code($order_info, $order_item){
			$use_status = 0;
			if(!empty($order_info['order_id'])){
				$time = time();
				// $order_item = get_field_by_where("shopping_order_item", "*", "order_id='{$order_info['order_id']}'");
				if($order_item){
					$use_code_data = array();
					$where = "school_id = '{$order_info['school_id']}' AND status = 1 ";
					if($order_info['order_type'] > 0 && $order_info['order_type'] < 4){
						//课程订单
						$where .= "AND course_id = '{$order_item['course_id']}'";
						$code_info = get_field_by_where("o2o_school_system_video_course_codes", "*", $where . " ORDER BY id ASC");

						if($code_info){
							//插入课程激活码使用记录
							$use_code_data['course_id'] = $order_item['course_id'];
							$use_code_data['course_type'] = $order_info['order_type'];
							$use_code_data['user_id'] = $order_info['buyer_user_id'];
							$use_code_data['code'] = $code_info['code'];
							$use_code_data['order_num'] = $order_info['order_num'];
							$use_code_data['school_id'] = $order_info['school_id'];
							$use_code_data['add_time'] = $time;
							$use_code_data['effective_time'] = $order_item['effective_time'];
							$this->db->insert("o2o_student_course", $use_code_data);
							if($this->db->insert_id() > 0){
								//修改实训激活码的使用状态
								$code_update_data = array("status" => 2, "use_uid" => $use_code_data['user_id'], "use_time" => $time);
								$this->db->where("id", $code_info['id']);
								$this->db->update("o2o_school_system_video_course_codes", $code_update_data);
								$use_status = 1;
							}
						}
					}elseif($order_info['order_type'] ==  4){
						//题库订单、获取题库激活码
						$where .= "AND subject_id = '{$order_item['course_id']}'";
						$code_info = get_field_by_where("o2o_school_system_topic_codes", "*", $where . " ORDER BY id ASC");

						if($code_info){
							//插入题库激活码使用记录
							$use_code_data['subject_id'] = $order_item['course_id'];
							$use_code_data['uid'] = $order_info['buyer_user_id'];
							$use_code_data['code'] = $code_info['code'];
							$use_code_data['order_num'] = $order_info['order_num'];
							$use_code_data['school_id'] = $order_info['school_id'];
							$use_code_data['use_time'] = $time;
							$use_code_data['effective_time'] = $order_item['effective_time'];
							$this->db->insert("o2o_student_system_topics", $use_code_data);
							if($this->db->insert_id() > 0){
								//修改题库激活码的使用状态
								$code_update_data = array("status" => 2, "use_uid" => $use_code_data['uid'], "use_time" => $time);
								$this->db->where("id", $code_info['id']);
								$this->db->update("o2o_school_system_topic_codes", $code_update_data);
								$use_status = 1;
							}
						}
					}elseif($order_info['order_type'] == 5){
						//实训订单、获取题库激活码
						$where .= "AND sx_id = '{$order_item['course_id']}'";
						$code_info = get_field_by_where("o2o_school_system_shixun_codes", "*", $where . " ORDER BY id ASC");

						if($code_info){
							//插入实训激活码使用记录
							$use_code_data['sx_id'] = $order_item['course_id'];
							$use_code_data['uid'] = $order_info['buyer_user_id'];
							$use_code_data['code'] = $code_info['code'];
							$use_code_data['order_num'] = $order_info['order_num'];
							$use_code_data['school_id'] = $order_info['school_id'];
							$use_code_data['use_time'] = $time;
							$use_code_data['effective_time'] = $order_item['effective_time'];
							$this->db->insert("o2o_student_system_shixun", $use_code_data);
							if($this->db->insert_id() > 0){
								//修改实训激活码的使用状态
								$code_update_data = array("status" => 2, "use_uid" => $use_code_data['uid'], "use_time" => $time);
								$this->db->where("id", $code_info['id']);
								$this->db->update("o2o_school_system_shixun_codes", $code_update_data);
								$use_status = 1;
							}
						}
					}
				}
			}
			return $use_status;
		}
	}